$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'order/orderinfo/mall/list',
        datatype: "json",
        colModel: [
            { label: '订单编号', name: 'orderId', index: 'order_Id', key: true , width: 120, align: 'center',
                formatter: function (value, options, row) {
                    return '<a href="javascript:;" onclick="return vm.getInfo(\''+ row.orderId +'\');">'+ row.orderId +'</a></li>';
                }
            },
            {
                label: '打印', width: 50, align: 'center', title: false,
                formatter: function (value, options, row) {
                    var actions = [];
                    actions.push('<a href="javascript:void(0);" onclick="return vm.printGoods(\'' + row.orderId + '\');">购</a>');
                    return actions.join('  ');
                }
            },
            { label: '会员名', name: 'memberName', index: '', width: 120 , align:'center'},
            { label: '商品总额', name: 'totalAmount', index: 'total_amount', width: 60 , align:'center'},
            { label: '应支付额', name: 'payableAmount', index: 'payable_amount', width: 60 , align:'center'},
            { label: '已支付额', name: 'payed', index: 'payed', width: 60 , align:'center'},
            { label: '订单状态', name: 'status', index: 'status', width: 60 , align:'center',
                formatter: function (value, options, row) {
                    var valueText = "";
                    var userData = $("#" + options.gid).jqGrid('getGridParam', 'userData');
                    $.each(userData.orderInfoStatusEnum, function (index, module) {
                        if (module.value == value) {
                            valueText = module.describe;
                            return false;
                        }
                    });
                    return valueText;
                }},
            { label: '平台来源', name: 'source', index: 'source', width: 60 , align:'center'},
            { label: '下单时间', name: 'createtime', index: 'createtime', width: 120 , align:'center'},
            { label: '支付状态', name: 'payStatus', index: 'pay_status', width: 60 , align:'center',
                formatter: function (value, options, row) {
                    return value == '1' ? '已支付' : '未支付';
                }},
            { label: '生产状态', name: 'productionStatus', index: 'production_status', width: 80 , align:'center',
                formatter: function (value, options, row) {
                    // '生产状态:1.待审核;2.待分配;3.生产中;4.生产完成;5.已发货;6.已完成;7.新开单(门店);11.已作废',
                    if (isBlank(value) || value == '1'){
                        // 分配的订单有待接单状态
                        var allocated = row.allocated;
                        if (allocated){
                            return '待接单';
                        }else {
                            return '生产中';
                        }
                    }else if (value == '3'){
                        return '生产中';
                    }else if (value == '4'){
                        return '生产完成';
                    }else if (value == '6'){
                        return '已完成';
                    }else {
                        return '';
                    }
                }
            },
            { label: '发货状态', name: 'shipStatus', index: 'ship_status', width: 60 , align:'center',
                formatter: function (value) {
                    return value == '1' ? '已发货' : '未发货';
                }},
            { label: '配送方式', name: 'pickUp', index: 'pick_up', width: 60 , align:'center',
                formatter: function (value, options, row) {
                    if (value){
                        return '自提';
                    }
                    return '非自提';
                }},
            { label: '收货人', name: 'shipName', index: 'ship_name', width: 80 , align:'center'},
            { label: '收货地址', name: 'shipAddr', index: 'ship_addr', width: 150 , align:'center'},
            { label: '客户留言', name: 'memo', index: 'memo', width: 100 , align:'center'},
            { label: '操作', name: '', index: '', width: 60 , align:'center',
                formatter: function (value, options, row) {
                    // 判断是否分配订单，有开始生产、生产完成操作
                    if (row.allocated){
                        var productionStatus = row.productionStatus;
                        if (productionStatus == null || productionStatus == 1){
                            return '<a href="javascript:;" onclick="return vm.produceStart(\''+ row.orderId +'\');">开始生产</a>';
                        }else if (productionStatus == 3){
                            return '<a href="javascript:;" onclick="return vm.produceFinish(\''+ row.orderId +'\');">生产完成</a>';
                        }
                    }
                    return '--';
                }},
        ],
        viewrecords: true,
        height: 700,
        rowNum: 25,
        rowList : [25,50,75],
        rownumbers: true,
        rownumWidth: 40,
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount",
            userdata: "userData"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        gridComplete:function(){
            // 隐藏grid底部滚动条
            $("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
            // 枚举参数
            var userData = $("#jqGrid").jqGrid('getGridParam', 'userData');
            vm.e.orderInfoStatusEnum = userData.orderInfoStatusEnum;
            vm.e.thirdMerchantTypeEnum = userData.thirdMerchantTypeEnum;
            vm.e.payTypeEnum = userData.payTypeEnum;
        }
    });
    // 显示序号
    $("#jqGrid").jqGrid('setLabel',0, '序号', '{width:80}');
});

var vm = new Vue({
    el:'#rrapp',
    data:{
        showList: true,
        showOrder: false,
        showLogi: false,
        fileTableVisible: false,
        orderInfo: {},
        erpOrder: {},
        orderItemList: [],
        orderLogisticsEntityList: [],
        userPaymentList: [],
        procedure: '',
        /* 枚举 */
        e:{
            payTypeEnum: [],
            addcartBuyTypeEnum:[],
            orderInfoStatusEnum:[],
            thirdMerchantTypeEnum:[],
            taxTypeEnum:[],
            goodsTypeEnum:[],
            taxContentEnum: [
                {text: '订单明细'},
                {text: '印刷品'},
                {text: '纸制品'},
                {text: '设计费'},
                {text: '铜版纸'},
                {text: '双胶纸'},
                {text: '白卡纸'},
                {text: '复印纸'},
                {text: '淋膜纸'}
            ],
        },
        /* 查询 */
        q:{
            orderId: '',
            memberName: '',
            status: '',
            orderType: '',
            beginCreatetime: '',
            endCreatetime: '',
            payStatus: '',
            shipStatus: '',
            productionStatus: ''
        },
        /* 源文件下载 */
        itemFile:{
            /* 订单商品集合下标标识，获得当前正在操作的商品元素 */
            itemIndex: 0,
            /* 正在操作商品的附件集合 */
            itemFiles: []
        },
        /* 打印快递单 */
        print: {
            orderInfo: {},
            orderItemList: []
        },
        /* 物流发货 */
        showSendDetail: true,       // 是否显示发货明细
        showLogiNo: true,           // 是否显示配送单号
        erpLogisticsEntity:{},
        logisticsTypeList:[],
        oderInfoEntity:{},
        orderItemEntityList:[],
    },
    methods: {
        /* 订单起始 */
        checkBeginDate: function () {
            WdatePicker({dateFmt:'yyyy-MM-dd',isShowClear:false, onpicking:function (dp) {
                    vm.q.beginCreatetime = dp.cal.getNewDateStr();
                }})
        },
        /* 订单结束 */
        checkEndDate: function () {
            WdatePicker({dateFmt:'yyyy-MM-dd',isShowClear:false, onpicking:function (dp) {
                    vm.q.endCreatetime = dp.cal.getNewDateStr();
                }})
        },
        /* 开始生产 */
        produceStart: function (orderId) {
            this.$confirm('是否确认开始生产?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                callback: function (f) {
                    if (f == 'confirm'){
                        $.ajax({
                            type: "GET",
                            url: baseURL + "order/factoryorder/produceStart",
                            contentType: "application/json",
                            data: {
                                orderId: orderId
                            },
                            success: function (r) {
                                if (r.code === 0) {
                                    alert('操作成功', function (index) {
                                        vm.reload();
                                    });
                                } else {
                                    alert(r.msg);
                                }
                            }
                        });
                    }
                }
            })
        },
        /* 生产完成 */
        produceFinish: function (orderId) {
            this.$confirm('是否确认生产完成?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                callback: function (f) {
                    if (f == 'confirm'){
                        $.ajax({
                            type: "GET",
                            url: baseURL + "order/factoryorder/produceFinish",
                            contentType: "application/json",
                            data: {
                                orderId: orderId
                            },
                            success: function (r) {
                                if (r.code === 0) {
                                    alert('操作成功', function (index) {
                                        vm.reload();
                                    });
                                } else {
                                    alert(r.msg);
                                }
                            }
                        });
                    }
                }
            })
        },
        /* 详情页面 */
        getInfo: function(orderId){
            $.get(baseURL + "order/orderinfo/mall/info/" + orderId, function(r){
                /* 实体类 */
                vm.erpOrder = r.erpOrder;
                vm.orderInfo = r.orderInfo;
                vm.orderItemList = r.orderItemList;
                vm.orderLogisticsEntityList = r.orderLogisticsEntityList;
                vm.userPaymentList = r.userPaymentList;
                vm.procedure = r.procedure;

                /* 枚举 */
                vm.e.addcartBuyTypeEnum = r.addcartBuyTypeEnum;
                vm.e.taxTypeEnum = r.taxTypeEnum;
                vm.e.goodsTypeEnum = r.goodsTypeEnum;

                vm.showList = false;
                vm.showLogi = false;
                vm.showOrder = true;
            });
        },
        /* 展示源文件 */
        itemFileShow: function (idx) {
            var itemId = vm.orderItemList[idx].itemId;
            $.ajax({
                type: "GET",
                url: baseURL + "order/useraccessory/userAccessorys/" + itemId,
                contentType: "application/json",
                data: [],
                success: function(r){
                    if(r.code === 0){
                        var goodsName = vm.orderItemList[idx].name;
                        vm.fileTableVisible = true;
                        vm.itemFile.itemIndex = idx;
                        vm.itemFile.itemFiles = r.list;
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        // 原文件下载
        itemFileDownload: function (data) {
            window.location.href = baseURL + "order/useraccessory/download/" + data.id;
        },
        reset: function () {
            vm.q.orderId = '';
            vm.q.memberName = '';
            vm.q.status = '';
            vm.q.orderType = '';
            vm.q.beginCreatetime = '';
            vm.q.endCreatetime = '';
            vm.q.payStatus = '';
            vm.q.shipStatus = '';
            vm.q.productionStatus = '';
            vm.reload();
        },
        query: function () {
            vm.reload();
        },
        reback: function () {
            vm.showList = true;
        },
        reload: function (event) {
            vm.showList = true;
            vm.showOrder = false;
            vm.showLogi = false;
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            $("#jqGrid").jqGrid('setGridParam',{
                page:page,
                postData:{
                    'orderId': vm.q.orderId,
                    'memberName': vm.q.memberName,
                    'status': vm.q.status,
                    'orderType': vm.q.orderType,
                    'beginCreatetime': vm.q.beginCreatetime,
                    'endCreatetime': vm.q.endCreatetime,
                    'payStatus': vm.q.payStatus,
                    'shipStatus': vm.q.shipStatus,
                    'productionStatus': vm.q.productionStatus,
                },
            }).trigger("reloadGrid");
        },
        // 打印
        print:function(id){
            //todo 预留打印
        },
        // 弹出送货单
        createPrintPage: function () {
            LODOP = getLodop();
            LODOP.PRINT_INIT("Lodop初始化");
            LODOP.SET_PRINT_PAGESIZE(3, 0, 0, "A4"); //第一个参数为1表示纵向
            LODOP.ADD_PRINT_HTM(0, "1%", "99%", 500, document.getElementById("printbox").innerHTML);
            /*增加超文本项*/
        },
        // 打印送货单
        printGoods: function (orderNo) {
            $.get(baseURL + "order/orderinfo/mall/printGoods?orderId=" + orderNo, function (r) {
                vm.print.orderInfo = r.orderInfo;
                vm.print.orderItemList = r.orderItemList;
                LODOP = getLodop();
                LODOP.PRINT_INIT("");
                layer.open({
                    type: 1,
                    skin: 'layui-layer-molv',
                    title: "打印送货单",
                    area: ['800px', '550px'],
                    shadeClose: false,
                    content: jQuery("#printGoods"),
                    btn: ['打印', '取消'],
                    btn1: function (index) {
                        vm.createPrintPage();
                        LODOP.PRINT();
                        // LODOP.PREVIEW();
                    }
                });
            });
        },
        // 获取订单物流信息
        send:function () {
            var orderIds = getSelectedRows();
            //先去重
            orderIds=vm.removeDuplicatedItem(orderIds);
            if(orderIds == null){
                return ;
            }
            if(orderIds.length!=1){
                this.$message("请勿勾选订单号不同项");
                return ;
            }
            var orderId=orderIds[0];
            var that = this
            $.ajax({
                type: "GET",
                url: baseURL + "order/orderinfo/mall/sendLogisticsInfo/" + orderId,
                contentType: "application/json",
                data: null,
                success: function(r){
                    if(r.code == 0){

                        vm.oderInfoEntity = r.oderInfoEntity;
                        vm.orderItemEntityList = r.orderItemEntityList;
						that.$refs.multipleTable.toggleAllSelection();
                        vm.area= JSON.parse(r.area);
                        vm.logisticsTypeList=r.logisticsTypeList;
                        var shipMobile = vm.oderInfoEntity.shipMobile;
                        var shipTel = vm.oderInfoEntity.shipTel;
                        var toPhone = shipMobile == null ? "" : shipMobile + "" + (shipTel == null ? "": ","+ shipTel);
                        vm.erpLogisticsEntity = {
                            toPeople: vm.oderInfoEntity.shipName,
                            toPhone:  toPhone,
                            toAddress: vm.oderInfoEntity.shipAddr,
                            toArea: vm.oderInfoEntity.shipArea,
                            toAreaId: vm.oderInfoEntity.shipAreaId,
                            sendType: 3,
                            logiType: 2
                        };
                        $.get(baseURL + "supp/sellerinfo/info", function(r){
                            var sellerinfo = r.sellerInfo;
                            Vue.set(vm.erpLogisticsEntity, 'fromPeople', sellerinfo.sellerName);
                            Vue.set(vm.erpLogisticsEntity, 'fromPhone', sellerinfo.sellerMobile);
                            Vue.set(vm.erpLogisticsEntity, 'fromAddress', sellerinfo.addr);
                            Vue.set(vm.erpLogisticsEntity, 'fromArea', sellerinfo.area);
                        });

                        vm.showList = false;
                        vm.showOrder = false;
                        vm.showLogi = true;
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        removeDuplicatedItem:function(arr){
            for(var i = 0; i < arr.length-1; i++){
                for(var j = i+1; j < arr.length; j++){
                    if(arr[i]==arr[j]){
                        arr.splice(j,1);
                        j--;
                    }
                }
            }
            return arr;
        },
        // 监听订单明细勾选change事件
        orderItemSelectionChange: function (row) {
            var list = new Array();
            for (var i = 0, orderItem; orderItem = row[i++];) {
                var logisticsItem = {
                    orderItemId: orderItem.itemId,
                    orderItemName: orderItem.name,
                    quantity: orderItem.nums,
                }
                list.push(logisticsItem);
            }
            vm.logisticsItemList = list;
        },
        // 参数验证
		validator: function () {
            if(vm.erpLogisticsEntity.logiType != 3){
                if (isBlank(vm.erpLogisticsEntity.logisticsId)) {
                    alert("物流方式不能为空");
                    return false;
                }
            }
            if (isBlank(vm.erpLogisticsEntity.toPeople)) {
                alert("收货人不能为空");
                return false;
            } else if (isBlank(vm.erpLogisticsEntity.toAreaId)) {
                alert(" 收货地区不能为空");
                return false;
            } else if (isBlank(vm.erpLogisticsEntity.toArea)) {
                alert("收货地址不能为空");
                return false;
            }
			return true;
		},
        /* 保存物流信息 */
        saveLogistics:function () {
			if (!vm.validator()) {
				return false;
			}
            // todo校验
            var erpLogisticsDto = {
                erpLogisticsEntity: vm.erpLogisticsEntity,
                erpLogisticsItemList: vm.logisticsItemList
            }
            erpLogisticsDto.erpLogisticsEntity.orderId =vm.oderInfoEntity.orderId;
            // 暂定为一样，如需修改再改
            erpLogisticsDto.erpLogisticsEntity.orderNo = vm.oderInfoEntity.orderId;
            erpLogisticsDto.erpLogisticsEntity.sellerId = vm.oderInfoEntity.supplierId;
            erpLogisticsDto.erpLogisticsEntity.fromPeople = vm.erpLogisticsEntity.fromPeople;
            erpLogisticsDto.erpLogisticsEntity.fromArea = vm.erpLogisticsEntity.fromArea;
            erpLogisticsDto.erpLogisticsEntity.fromAddress = vm.erpLogisticsEntity.fromAddress;
            erpLogisticsDto.erpLogisticsEntity.fromPhone = vm.erpLogisticsEntity.fromPhone;
            // 防止后台校验报错
            erpLogisticsDto.erpLogisticsEntity.productionId=0;
            $.ajax({
                type: "POST",
                url: baseURL + "logistics/erplogistics/saveOrderLogisticsInfo",
                contentType: "application/json",
                data: JSON.stringify(erpLogisticsDto),
                success: function (r) {
                    if (r.code === 0) {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    } else {
                        alert(r.msg);
                    }
                }
            });
        },
        logiTypeChange: function (value) {
            for (var i = 0, logisticsType; logisticsType = vm.logisticsTypeList[i++];) {
                // 紫云物流 不填写配送单号
                if (logisticsType.logisticsId == value){
                    vm.erpLogisticsEntity.logiCompany = logisticsType.logisticsName;
                    if (logisticsType.logisticsName.indexOf("紫云-") == 0){
                        vm.showLogiNo = false;
                        break;
                    }
                }else {
                    vm.showLogiNo = true;
                }
            }
        },
        sendTypeChange: function (value) {
            if (value == 1) {
                vm.showSendDetail = false;
            } else {
                vm.showSendDetail = true;
            }
        },
        handleItemChange: function (val) {
            var values = val.join(',').split(',');
            var areaId = values[val.length - 1];
            vm.erpLogisticsEntity.toAreaId = areaId;

            var lableObj = getCascaderObj(val, vm.area);
            var lable = lableObj.join(',').replace(new RegExp(',', 'g'), ' ');
            vm.erpLogisticsEntity.toArea = lable;
        },
        /* 门店生产 */
        produce: function (orderId) {
            this.$confirm('确认转到门店生产吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                callback: function (f) {
                    if (f == 'confirm'){
                        $.ajax({
                            type: "GET",
                            url: baseURL + "order/orderinfo/mall/produce",
                            contentType: "application/json",
                            data: {
                                orderId: orderId
                            },
                            success: function (r) {
                                if (r.code === 0) {
                                    alert('操作成功', function (index) {
                                        vm.reload();
                                    });
                                } else {
                                    alert(r.msg);
                                }
                            }
                        });
                    }
                }
            })
        },
        /* 打印快递单 */
        printEMS: function() {
            //初始化快递单
            LODOP = getLodop();
            LODOP.PRINT_INIT("初始化快递单");
            LODOP.SET_PRINT_PAGESIZE(1, 2200, 1200 , "");
            LODOP.SET_PRINT_STYLE("FontSize", 9);
            LODOP.ADD_PRINT_TEXT(101, 110, 150, 25, vm.sellerInfo.sellerName);  //寄件人姓名
            LODOP.ADD_PRINT_TEXT(101, 295, 150, 25, vm.sellerInfo.area);  //始发地城市
            if (vm.radio == 1) {  //韵达
                LODOP.ADD_PRINT_TEXT(126, 110, 302, 25, vm.sellerInfo.doorheadName);  //单位名称
                LODOP.ADD_PRINT_TEXT(151, 110, 302, 25, vm.sellerInfo.addr);  //寄件地址1
            }else if (vm.radio == 2) { //中通
                LODOP.ADD_PRINT_TEXT(126, 110, 302, 25, vm.sellerInfo.addr);  //寄件地址1
                LODOP.ADD_PRINT_TEXT(151, 110, 302, 25, vm.sellerInfo.doorheadName );  //单位名称
            }
            LODOP.ADD_PRINT_TEXT(201, 110, 150, 25, vm.sellerInfo.sellerMobile); //联系电话1
            LODOP.ADD_PRINT_TEXT(201, 254, 150, 25, vm.sellerInfo.shipZip);  //邮政编码1

            LODOP.ADD_PRINT_TEXT(101, 470, 150, 25, vm.erpOrder.shipName);  //收件人姓名
            LODOP.ADD_PRINT_TEXT(101, 645, 150, 25, vm.erpOrder.shipArea);  //目的地城市
            if (vm.radio == 1) {
                LODOP.ADD_PRINT_TEXT(126, 470, 302, 25, vm.erpOrder.memberName);  //单位名称
                LODOP.ADD_PRINT_TEXT(151, 470, 302, 25, vm.erpOrder.shipAddr);  //收件地址2
            }else if (vm.radio == 2) {
                LODOP.ADD_PRINT_TEXT(126, 470, 302, 25, vm.erpOrder.shipAddr);  //收件地址2
                LODOP.ADD_PRINT_TEXT(151, 470, 302, 25, vm.erpOrder.memberName);  //单位名称
            }

            LODOP.ADD_PRINT_TEXT(201, 470, 150, 25, vm.erpOrder.shipMobile);  //联系电话2
            LODOP.ADD_PRINT_TEXT(201, 596, 150, 25, vm.erpOrder.shipZip);  //邮政编码2
            LODOP.PRINT();
            // LODOP.PREVIEW();
        },
    }
});

/**
 * 省市区级联选择
 */
function getCascaderObj(val, opt) {
    return val.map(function (value, index, array) {
        for (var itm in opt) {
            if (opt[itm].value == value) {
                var label = opt[itm].label;
                opt = opt[itm].children;
                return label;
            }
        }
        return null;
    });
}

/** 数字金额大写转换(可以处理整数,小数,负数) */
function smalltoBIG(n) {
    var fraction = ['角', '分'];
    var digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
    var unit = [['元', '万', '亿'], ['', '拾', '佰', '仟']];
    var head = n < 0 ? '欠' : '';
    n = Math.abs(n);

    var s = '';

    for (var i = 0; i < fraction.length; i++) {
        s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
    }
    s = s || '整';
    n = Math.floor(n);

    for (var i = 0; i < unit[0].length && n > 0; i++) {
        var p = '';
        for (var j = 0; j < unit[1].length && n > 0; j++) {
            p = digit[n % 10] + unit[1][j] + p;
            n = Math.floor(n / 10);
        }
        s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
    }
    return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整');
}